/*
 * 文件名：EntitySupport.java
 * 描述： 
 * 修改人： wangshi
 * 修改时间：2012-8-23
 */
package com.ws.base.common.entity;

import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import com.ws.base.common.WSAppLogger;

import net.sf.json.JSON;
import net.sf.json.JSONSerializer;

/**
 * EntitySupport
 * 
 * @author wangshi
 * @version
 * @since
 */
public class EntitySupport implements Serializable {
    /** serialVersionUID */
    private static final long serialVersionUID = -4400735210642490081L;

    private final String getMenthodPrefix = "get";

    private WSAppLogger log = WSAppLogger.getWSAppLogger(this.getClass());

    public String toString() {
        Map<String, Object> _map = queryGetMethod();

        if (_map.isEmpty()) {
            return super.toString();
        }

        Map<String, Object> map = new HashMap<String, Object>();
        map.put(this.getClass().getName(), _map);
        JSON json = JSONSerializer.toJSON(map);
        return json.toString();
    }

    private Map<String, Object> queryGetMethod() {
        Class<?> clazz = this.getClass();

        Method[] methods = clazz.getMethods();

        Map<String, Object> map = new HashMap<String, Object>();

        try {
            for (Method method : methods) {
                if (method.getName().startsWith(getMenthodPrefix)
                        && method.getName().length() > 3) {
                    Object _obj = method.invoke(this);
                    map.put(getFieldByMethodName(method.getName()), _obj);
                }
            }
        } catch (IllegalArgumentException e) {
            log.error(e);
        } catch (IllegalAccessException e) {
            log.error(e);
        } catch (InvocationTargetException e) {
            log.error(e);
        }
        return map;
    }

    private String getFieldByMethodName(String methodName) {
        int size = methodName.length();
        String prefix = methodName.substring(3, 4).toLowerCase();
        if (size > 4) {
            prefix += methodName.substring(4, size);
        }
        return prefix;
    }

    public Map<String, Object> toMap() {
        return queryGetMethod();
    }

}
